<template>
  <div class="datepicker">
    <van-popup v-model="showDatePicker" round position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        :type="dateType"
        title="选择年月"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @confirm="onConfirm"
        @cancel="onCancel"
        show-toolbar
      />
    </van-popup>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showDatePicker: false,
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(2100, 11, 1),
      currentDate: new Date()
    };
  },
  props: {
    show: {
      default: false,
      type: Boolean
    },
    defaultDate: {
      default() {
        return new Date();
      }
    },
    dateType: {
      default: 'year-month',
      type: String
    }
  },
  watch: {
    show(newVal) {
      this.showDatePicker = newVal;
    },
    defaultDate(newVal) {
      this.currentDate = new Date(newVal);
    },
    showDatePicker(newval) {
      this.$emit('hide', {
        showDatePicker: newval
      });
    }
  },
  methods: {
    formatter(type, val) {
      if (type === 'year') {
        return `${val}年`;
      } else if (type === 'month') {
        return `${val}月`;
      }
      return val;
    },
    onConfirm(d) {
      this.showDatePicker = false;
      this.$emit('fetchData', {
        value: `${this.currentDate.getFullYear()}-${((this.currentDate.getMonth() + 1) + '').padStart('2', '0')}`,
        originValue: this.currentDate,
        showDatePicker: this.showDatePicker
      });
    },
    onCancel() {
      this.showDatePicker = false;
      this.$emit('cancel', {
        showDatePicker: this.showDatePicker
      });
    }
  }
};
</script>

<style lang="less" scoped>
.datepicker {
  /deep/.van-picker__toolbar {
    height: 80px;
    line-height: 80px;
    padding: 10px 20px;
    .van-picker__cancel,
    .van-picker__title,
    .van-picker__confirm {
      font-size: 34px;
    }
    .van-picker__title {
      line-height: 80px;
    }
  }
  /deep/.van-picker-column__item {
    .van-ellipsis {
      font-size: 34px;
    }
  }
}
</style>
